package com.dmsdbj.itoo.graduate.service.impl;

import com.dmsdbj.itoo.graduate.dao.CompanyDao;
import com.dmsdbj.itoo.graduate.dao.RegionInformationDao;
import com.dmsdbj.itoo.graduate.entity.*;
import com.dmsdbj.itoo.graduate.entity.ext.CompanyModel;
import com.dmsdbj.itoo.graduate.entity.ext.CompanySalaryModel;
import com.dmsdbj.itoo.graduate.entity.ext.TechnologyModel;
import com.dmsdbj.itoo.graduate.facade.impl.CompanyFacadeImpl;
import com.dmsdbj.itoo.graduate.mybatisexample.*;
import com.dmsdbj.itoo.graduate.service.*;
import com.dmsdbj.itoo.tool.base.dao.BaseDao;
import com.dmsdbj.itoo.tool.base.service.impl.BaseServiceImpl;
import com.dmsdbj.itoo.tool.tenancy.TenancyContext;
import com.dmsdbj.itoo.tool.uuid.BaseUuidUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.security.cert.CRLReason;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author sxm
 * create:2017-11-16 14:31:07
 * DESCRIPTION
 */
@Service("companyService")
public class CompanyServiceImpl extends BaseServiceImpl<CompanyEntity, CompanyExample> implements CompanyService {

    //打印日志相关
    private static final Logger logger = LoggerFactory.getLogger(CompanyFacadeImpl.class);

    //注入companyDao
    @Resource
    private CompanyDao companyDao;
    @Resource
    private PersonCompanyRelationService personCompanyRelationService;
    @Resource
    private SalaryService salaryService;
    @Resource
    private CompanySkillRelationService companySkillRelationService;
    @Resource
    private SkillPointService skillPointService;
    @Resource
    private PictureService pictureService;


    @Resource
    private RegionInformationDao regionInformationDao;
    /**
     * 让BaseServiceImpl获取到Dao
     *
     * @return BaseDao<CompanyEntity, CompanyExample>
     */
    @Override
    public BaseDao<CompanyEntity, CompanyExample> getRealDao() {
        return this.companyDao;
    }

    /**
     * 添加公司信息-宋学孟-2017年11月23日
     *
     * @param companyModelList 公司及关系表实体
     * @return 影响条数
     * @Deprecated 不满足显示已添加薪资的需求，不使用见addCompany方法
     */
    @Deprecated
    @Transactional(rollbackFor = Exception.class)
    public int addCompanyOld(List<CompanyModel> companyModelList) {

        int companyCount = 0;
        int count1 = 0;

        //如果该学员之前查询有添加的公司，编辑=先删除再添加
        //考虑怎样保证事务，只是异常回滚吗，在循环中这样判断就不准了，综合>0
        if (CollectionUtils.isEmpty(companyModelList)) {
            logger.error("要添加的公司信息为空");
            return 0;
        }
        //获取userId
        String userId = companyModelList.get(0).getUserId();
        String operator = TenancyContext.UserID.get();
        //删除原有的数据

        //删除公司---暂时由个人维护---无法实现
        /*
        CompanyExample companyExample = new CompanyExample();
        CompanyCriteria companyCriteria = companyExample.createCriteria();
        companyCriteria.andIdEqualTo(companyModel.getCompanyId());
        companyCriteria.andIsDeleteEqualTo((byte)0);
        int deleteCount0 = this.deleteByExample(companyExample, userId); //无法实现功能，如果先删除一个公司则根据公司id不能删除所有的原有的公司
        */

        PersonCompanyRelationExample example = new PersonCompanyRelationExample();
        PersonCompanyRelationCriteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andIsDeleteEqualTo((byte) 0);
                /*第一次添加可能deletecount1=0*/
        personCompanyRelationService.deleteByExample(example, operator);

        CompanySkillRelationExample example1 = new CompanySkillRelationExample();
        CompanySkillRelationCriteria criteria1 = example1.createCriteria();
        criteria1.andOperatorIdEqualTo(userId);
        criteria.andIsDeleteEqualTo((byte) 0);
                /*第一次添加或者上一次没有选技术点则没有可删除的*/
        companySkillRelationService.deleteByExample(example1, operator);

        for (CompanyModel companyModel : companyModelList) { //TODO 待优化
            if (StringUtils.isEmpty(companyModel.getUserId())) {
                logger.error("未获取到用户id");
                return 0;
            }


            /*如果有单独的页面维护公司信息则个人添加公司不需要添加具体的公司信息，只需要维护关系*/
            /*如果有单独维护的 页面也可以有用户添加，只是也可以下拉，如果有改公司就直接选择,故companyCount可能为0*/
            String companyId = BaseUuidUtils.base58Uuid();
            CompanyEntity companyEntity = new CompanyEntity();
            BeanUtils.copyProperties(companyModel, companyEntity);
            companyEntity.setId(companyId);
            companyCount = this.insert(companyEntity);

            String personCompanyId = BaseUuidUtils.base58Uuid();
            companyModel.setCompanyId(companyId);

            //插入到关系表中
            PersonCompanyRelationEntity personCompanyRelationEntity = new PersonCompanyRelationEntity();
            BeanUtils.copyProperties(companyModel, personCompanyRelationEntity);
            personCompanyRelationEntity.setId(personCompanyId);
            personCompanyRelationEntity.setUserId(userId);
            count1 = personCompanyRelationService.insert(personCompanyRelationEntity);

            //添加技术点相关表
            if (!CollectionUtils.isEmpty(companyModel.getSkillIds())) {
                for (String skillId : companyModel.getSkillIds()) {
                    CompanySkillRelationEntity companySkillRelationEntity = new CompanySkillRelationEntity();
                    companySkillRelationEntity.setCompanyId(companyId);
                    companySkillRelationEntity.setSkillId(skillId);
                    companySkillRelationEntity.setId(BaseUuidUtils.base58Uuid());

                    companySkillRelationService.insert(companySkillRelationEntity);
                }
            }

            if (!CollectionUtils.isEmpty(companyModel.getPictureUrls())) {
                List<String> pictureUrls = companyModel.getPictureUrls();
                if (!StringUtils.isEmpty(pictureUrls)) {
                    for (String pictureUrl : pictureUrls) {
                        String fastdfsUrl = pictureUrl.substring(21, pictureUrl.length());
                        pictureService.addPicture(fastdfsUrl, personCompanyId);
                    }
                }
            }
        }
        return companyCount + count1 - 1;
    }

    /**
     * 添加公司信息-宋学孟-2017年11月23日
     *
     * @param companyModelList 公司及关系表实体
     * @return 影响条数
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addCompany(List<CompanyModel> companyModelList) {

        int companyCount = 0;
        int relationCount = 0;
        int editCompany = 0;
        int editRelation = 0;

        //如果该学员之前查询有添加的公司，编辑=先删除再添加
        //考虑怎样保证事务，只是异常回滚吗，在循环中这样判断就不准了，综合>0
        if (CollectionUtils.isEmpty(companyModelList)) {
            logger.error("要添加的公司信息为空");
            return 0;
        }
        //获取userId
        String userId = companyModelList.get(0).getUserId();
        String operator = TenancyContext.UserID.get();


        for (CompanyModel companyModel : companyModelList) { //TODO 待优化
            if (StringUtils.isEmpty(companyModel.getUserId())) {
                logger.error("未获取到用户id");
                return 0;
            }

            //如果personCompanyId有值，则说明是修改update，如果personCompanyId为空，则说明是新数据insert
            String personCompanyId = companyModel.getPersonCompanyId();
            if (StringUtils.isEmpty(personCompanyId)) {
                String companyId = BaseUuidUtils.base58Uuid();
                String regionId = BaseUuidUtils.base58Uuid();
                CompanyEntity companyEntity = new CompanyEntity();
                BeanUtils.copyProperties(companyModel, companyEntity);
                companyEntity.setId(companyId);
                companyEntity.setRegionId(regionId);
                companyCount = this.insert(companyEntity);

                personCompanyId = BaseUuidUtils.base58Uuid(); //可以不生成
                companyModel.setCompanyId(companyId);

                //地址信息存入region表
                RegionInformationEntity regionInformationEntity =new RegionInformationEntity();
                regionInformationEntity.setId(regionId);
                regionInformationEntity.setLat(companyModel.getLat());
                regionInformationEntity.setLng(companyModel.getLng());
                regionInformationEntity.setPoiId(companyModel.getPoiId());
                regionInformationEntity.setDictionaryAddressId("5vga8R8f94HgiPBTnyXBNT");
                regionInformationEntity.setRegionAddress(companyModel.getRegionAddress());

                regionInformationDao.insert(regionInformationEntity);


                //插入到关系表中
                PersonCompanyRelationEntity personCompanyRelationEntity = new PersonCompanyRelationEntity();
                BeanUtils.copyProperties(companyModel, personCompanyRelationEntity);
                personCompanyRelationEntity.setId(personCompanyId);
                personCompanyRelationEntity.setUserId(userId);
                relationCount = personCompanyRelationService.insert(personCompanyRelationEntity);

                //添加技术点相关表
//                if (!CollectionUtils.isEmpty(companyModel.getSkillIds())) {
//                    for (String skillId : companyModel.getSkillIds()) {
//                        CompanySkillRelationEntity companySkillRelationEntity = new CompanySkillRelationEntity();
//                        companySkillRelationEntity.setCompanyId(companyId);
//                        companySkillRelationEntity.setSkillId(skillId);
//                        companySkillRelationEntity.setId(BaseUuidUtils.base58Uuid());
//
//                        companySkillRelationService.insert(companySkillRelationEntity);
//                    }
//                }

//                if (!CollectionUtils.isEmpty(companyModel.getPictureUrls())) {
//                    List<String> pictureUrls = companyModel.getPictureUrls();
//                    if (!StringUtils.isEmpty(pictureUrls)) {
//                        for (String pictureUrl : pictureUrls) {
//                            String fastdfsUrl = pictureUrl.substring(21, pictureUrl.length());
//                            pictureService.addPicture(fastdfsUrl, personCompanyId);
//                        }
//                    }
//                }

            } else {
                //更新公司表
                String companyId = companyModel.getCompanyId();
                CompanyEntity companyEntity = new CompanyEntity();
                BeanUtils.copyProperties(companyModel, companyEntity);
                CompanyExample companyExample = new CompanyExample();
                CompanyCriteria companyCriteria = companyExample.createCriteria();
                companyCriteria.andIdEqualTo(companyId);
                companyCriteria.andIsDeleteEqualTo((byte) 0);
                editCompany = this.updateByExample(companyEntity,companyExample);

                 //假如PoiId是有值的，则可以进行修改
                String PoiId = companyModel.getPoiId();
                if (!StringUtils.isEmpty(PoiId)) {
                    //更新到region地图表
                    RegionInformationEntity regionInformationEntity = new RegionInformationEntity();
                    regionInformationEntity.setLat(companyModel.getLat());
                    regionInformationEntity.setLng(companyModel.getLng());
                    regionInformationEntity.setPoiId(companyModel.getPoiId());
                    regionInformationEntity.setRegionAddress(companyModel.getRegionAddress());

                    RegionInformationExample example1 = new RegionInformationExample();
                    RegionInformationCriteria criteria1 = example1.createCriteria();
                    criteria1.andIdEqualTo(companyModel.getRegionId());
                    criteria1.andIsDeleteEqualTo((byte) 0);
                    regionInformationDao.updateByExample(regionInformationEntity,example1);
                }

                //更新到关系表中
                PersonCompanyRelationEntity personCompanyRelationEntity = new PersonCompanyRelationEntity();
                BeanUtils.copyProperties(companyModel, personCompanyRelationEntity);
                PersonCompanyRelationExample example = new PersonCompanyRelationExample();
                PersonCompanyRelationCriteria criteria = example.createCriteria();
                criteria.andIdEqualTo(personCompanyId);
                criteria.andIsDeleteEqualTo((byte) 0);

                editRelation = personCompanyRelationService.updateByExample(personCompanyRelationEntity,example);

                //更新技术点相关表--暂时没改--暂时没有使用
//                if (!CollectionUtils.isEmpty(companyModel.getSkillIds())) {
//                    for (String skillId : companyModel.getSkillIds()) {
//                        CompanySkillRelationEntity companySkillRelationEntity = new CompanySkillRelationEntity();
//                        companySkillRelationEntity.setCompanyId(companyId);
//                        companySkillRelationEntity.setSkillId(skillId);
//                        companySkillRelationEntity.setId(BaseUuidUtils.base58Uuid());
//
//                        companySkillRelationService.insert(companySkillRelationEntity);
//                    }
//                }
                //更新图片--暂时没改--暂时没有使用
//                if (!CollectionUtils.isEmpty(companyModel.getPictureUrls())) {
//                    List<String> pictureUrls = companyModel.getPictureUrls();
//                    if (!StringUtils.isEmpty(pictureUrls)) {
//                        for (String pictureUrl : pictureUrls) {
//                            String fastdfsUrl = pictureUrl.substring(21, pictureUrl.length());
//                            pictureService.addPicture(fastdfsUrl, personCompanyId);
//                        }
//                    }
//                }
            }
        }
        return editCompany+editRelation + companyCount+relationCount -1;
    }

    /**
     * 删除公司-宋学孟-2017年11月23日
     *
     * @param companyId 公司id
     * @param userId    学员id
     * @return 影响条数
     */
    @Override
    public int deleteCompany(String companyId, String userId, String operatorId) {

        int count = 0;
        int count1 = 0;
        String operator = TenancyContext.UserID.get();
        if (!StringUtils.isEmpty(companyId)) {
            count = this.deleteById(companyId, operator);
        }
        if (!StringUtils.isEmpty(companyId) && !StringUtils.isEmpty(operator)) {
            PersonCompanyRelationExample personCompanyRelationExample = new PersonCompanyRelationExample();
            PersonCompanyRelationCriteria personCompanyCriteria = personCompanyRelationExample.createCriteria();
            personCompanyCriteria.andCompanyIdEqualTo(companyId);
            personCompanyCriteria.andUserIdEqualTo(userId);
            personCompanyCriteria.andIsDeleteEqualTo((byte) 0);
            count1 = personCompanyRelationService.deleteByExample(personCompanyRelationExample, operator);
        }
        return count + count1 - 1;
    }

    /**
     * 修改公司相关信息-2017年11月25日
     *
     * @param companyModel 公司及关系表实体
     * @return 影响条数
     */
    @Deprecated
    @Override
    public int updateCompany(CompanyModel companyModel) {
        int count = 0;
        int count1 = 0;
        if (companyModel != null && !StringUtils.isEmpty(companyModel.getCompanyName())) {
            CompanyEntity companyEntity = new CompanyEntity();
            BeanUtils.copyProperties(companyModel, companyEntity);
            companyEntity.setId(companyModel.getCompanyId());
            count = this.updateById(companyEntity);
        }
        if (companyModel != null && !StringUtils.isEmpty(companyModel.getUserId()) && !StringUtils.isEmpty(companyModel.getCompanyId())) {
            PersonCompanyRelationEntity personCompanyRelationEntity = new PersonCompanyRelationEntity();
            BeanUtils.copyProperties(companyModel, personCompanyRelationEntity);
            //根据条件更新
            PersonCompanyRelationExample personCompanyRelationExample = new PersonCompanyRelationExample();
            PersonCompanyRelationCriteria personCompanyRelationCriteria = personCompanyRelationExample.createCriteria();
            personCompanyRelationCriteria.andCompanyIdEqualTo(companyModel.getCompanyId());
            personCompanyRelationCriteria.andIsDeleteEqualTo((byte) 0);
            count1 = personCompanyRelationService.updateByExample(personCompanyRelationEntity, personCompanyRelationExample);
        }
        return count + count1 - 1;
    }

    /**
     * 查询公司相关信息-2017年11月25日
     *
     * @param userId 学员Id
     * @return 公司实体list
     */
    @Override
    public CompanyModel selectCompanyByUserId(String userId) {

        CompanyModel companyModel = companyDao.selectCompanyByUserId(userId).get(0);
        //TODO 应该是list
        List<String> picUrl = pictureService.selectPictureById(companyModel.getPersonCompanyId());
        companyModel.setPictureUrls(picUrl);
        return companyModel;
    }

    /**
     * 查询公司相关信息-所有公司（添加流程）-2018年1月18日
     *
     * @param userId 学员Id
     * @return 公司实体list
     */
    @Override
    public List<CompanyModel> selectCompanysByUserId(String userId) {

        List<CompanyModel> companyModelList = companyDao.selectCompanyByUserId(userId);
        for (CompanyModel companyModel : companyModelList) {
            List<String> pictureUrls = pictureService.selectPictureById(companyModel.getPersonCompanyId());
            companyModel.setPictureUrls(pictureUrls);
        }
        return companyDao.selectCompanyByUserId(userId);
    }

    /**
     * 查询学员工作经历和薪资-宋学孟-2017年12月4日
     *
     * @param userId 用户id
     * @return 公司实体list
     */
    @Override
    public List<CompanySalaryModel> selectCompanySalaryByUserId(String userId, int page, int pageSize) {

        if (StringUtils.isEmpty(userId)) {
            logger.error("查询学员工作经历和薪资--参数为空");
            return new ArrayList<>();
        }

        PersonCompanyRelationExample personCompanyRelationExample = new PersonCompanyRelationExample();
        PersonCompanyRelationCriteria personCompanyRelationCriteria = personCompanyRelationExample.createCriteria();
        personCompanyRelationCriteria.andUserIdEqualTo(userId);

        List<PersonCompanyRelationEntity> personCompanyRelationEntityList = personCompanyRelationService.selectByExample(personCompanyRelationExample);
        if (CollectionUtils.isEmpty(personCompanyRelationEntityList)) {
            logger.error("查询个人和公司关系表--未查到结果");
            return new ArrayList<>();
        }
        List<String> personCompanyIdList = new ArrayList<>();
        for (PersonCompanyRelationEntity personCompanyRelationEntity : personCompanyRelationEntityList) {
            if (!StringUtils.isEmpty(personCompanyRelationEntity.getId())) {
                personCompanyIdList.add(personCompanyRelationEntity.getId());
            }
        }
        if (CollectionUtils.isEmpty(personCompanyIdList)) {
            logger.error("查询个人和公司关系表，关系id为空");
            return new ArrayList<>();


        }
        List<SalaryEntity> salaryEntityList = salaryService.pageSelectSalaryInfoByRelationIds(personCompanyIdList, page, pageSize);

        if (CollectionUtils.isEmpty(salaryEntityList)) {
            logger.error("查询个人和公司关系表，关系id为空");
            return new ArrayList<>();
        }
        List<CompanySalaryModel> companySalaryModelList = new ArrayList<>();
        for (SalaryEntity salaryEntity : salaryEntityList) {
            CompanySalaryModel companySalaryModel = new CompanySalaryModel();
            BeanUtils.copyProperties(salaryEntity, companySalaryModel);
            companySalaryModelList.add(companySalaryModel);
        }

        List<CompanyModel> companyModelList = companyDao.selectCompanyByUserId(userId);
        if (!CollectionUtils.isEmpty(companyModelList)) {
            Map<String, String> companyNameMap = new HashMap<>();
            for (CompanyModel companyModel : companyModelList) {
                if (!StringUtils.isEmpty(companyModel.getPersonCompanyId()) && !StringUtils.isEmpty(companyModel.getCompanyName())) {
                    companyNameMap.put(companyModel.getPersonCompanyId(), companyModel.getCompanyName());
                }
            }
            for (CompanySalaryModel companySalaryModel1 : companySalaryModelList) {
                if (!StringUtils.isEmpty(companySalaryModel1.getPcRelationId())) {
                    String personCompanyId = companySalaryModel1.getPcRelationId();
                    companySalaryModel1.setCompanyName(companyNameMap.get(personCompanyId));
                }
            }
        }

        return companySalaryModelList;


    }

    /**
     * 分页查询学员工作经历和薪资-宋学孟-2018年2月8日
     *
     * @param userId 用户id
     * @return 公司薪资list
     */
    @Deprecated
    @Override
    public PageInfo<CompanySalaryModel> selectCompanySalaryPageByUserId(String userId, int page, int pageSize) {

        PageHelper.startPage(page, pageSize);
        List<CompanySalaryModel> companySalaryModelList = this.selectCompanySalaryByUserId(userId, page, pageSize);
        return new PageInfo<>(companySalaryModelList);

    }

    /**
     * 查询所有技术点的类别和详细技术点-宋学孟-2018年1月13日
     *
     * @return 技术点list
     */
    @Override
    public List<TechnologyModel> selectSkillPoint() {

        return skillPointService.selectAllTechnology();
    }

    /**
     * 保存上传图片的路径（一张）-宋学孟-2018年1月14日
     *
     * @param pictureUrl 图片url
     * @param keyId      关联外键id
     * @return 影响条数
     */
    @Override
    public int addPictureUrl(String pictureUrl, String keyId) {

        return pictureService.addPicture(pictureUrl, keyId);
    }

    /**
     * 根据相应的id，查询对应的实体（包含url）-宋学孟-2018年1月14日
     *
     * @param keyId 关联外键id
     * @return 图片url列表
     */
    @Deprecated
    @Override
    public List<String> selectPictureById(String keyId) {

        return pictureService.selectPictureById(keyId);
    }
}
